<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

class JFX_Module_Imager extends JFX_Module
{
    public $keyname = 'imager';
    public $title = 'Image Management';
    public $imager_config = array();
    public $dependencies = array(
        array(
            'keyname' => 'iusers',
            'version' => '0.1.0'
        )
    );
    public $version = '0.2.9';

    public function __construct(){
        parent::__construct();
		$this->title = $this->lang('module_title');
        $this->loadConfig();
        $this->garbageCollection();
    }




    function garbageCollection(){
        $tree = $this->getFolderHeirarchy();
        foreach($tree as $file){
            $this->doGarbageCollection($file);
        }
    }

    function doGarbageCollection($file){
        if(is_object($file) && $file instanceof JFX_Data_File){
            if(!file_exists($file->getAbsolutePath())){
                $file->delete();
            }
        }else{
            if(is_array($file)){
                // directory
                foreach($file['files'] as $newFile){
                    $this->doGarbageCollection($newFile);
                }
                foreach($file['subfolders'] as $newFile){
                    $this->doGarbageCollection($newFile);
                }

            }
        }
    }


function makeTree(&$tree, &$moduleObj, $showFiles=false, $folderUrl='', $fileUrl='', $folderClick='', $fileClick=''){
	ob_start();

        if($folderUrl==''){
            $folderUrl = $moduleObj->adminUrl.'/browse/?folder=:|folder|:';
        }
        if($fileUrl==''){
            $fileUrl = ':|url|:';
        }



	foreach($tree as $branch){
		$url = str_replace(':|folder|:', $branch['id'], $folderUrl);
		echo '<li>';
		$click = '';
		if($folderClick!=''){
			$click = str_replace(':|folder|:', $branch['id'], ' onclick="'.$folderClick.'" ');
		}
		echo '<a href="'.$url.'" '.$click.'>'.$branch['title'].'</a>';
		if(is_array($branch['subfolders']) && count($branch['subfolders'])>0){
			echo '<ul>'.$moduleObj->makeTree($branch['subfolders'], $moduleObj, $showFiles, $folderUrl, $fileUrl, $folderClick, $fileClick).'</ul>';
		}
                if($showFiles){
                    echo '<ul>';
                    foreach($branch['files'] as $k=>$file){
                        $click = '';
                        if($fileClick!=''){
                            $click = str_replace(':|url|:', $moduleObj->imageUrl.'/serve.php?absolutepath='.htmlentities($file->getAbsolutePath()), $fileClick);
							$click = str_replace(':|path|:', htmlentities($file->meta['filepath']), $click);
							$click = str_replace(':|filename|:', htmlentities($file->meta['filename']), $click);
							$click = ' onclick="'.$click.'" ';
                        }
                        $url = str_replace(':|url|:',  $moduleObj->imageUrl.'/serve.php?absolutepath='.urlencode($file->getAbsolutePath()), $fileUrl);
						$url = str_replace(':|path|:', urlencode($file->meta['filepath']), $url);
						$url = str_replace(':|filename|:', urlencode($file->meta['filename']), $url);
                        echo '<li><a href="'.$url.'" '.$click.'>'.urlencode($file->meta['friendly_name']).'</a></li>';
                    }
                    echo '</ul>';
                }
		echo '</li>';
	}

	$res = ob_get_contents();
	ob_end_clean();
	return $res;
}




    function LoadConfig(){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        // make sure we have been installed!

        if(!JFX_Module::isInstalled($this->keyname)) return;

        $config = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}imager_config");

        if($config === false) return;
        foreach($config as $k=>$v){
            $this->imager_config[$v['k']] = $v['v'];
        };
    }




    public function admin($url, $dirname){
        //$this->resetLanguages();
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $SMARTY->assign('actionUrl', $url);
        $LANG = JFX::registry('lang');
        $THEME = JFX::registry('JFX_Theme');

		$req = explode('imager', $url);
		$req = explode('/', trim($req[1], '/'));

		if(count($req)<0){
			$req[0] = 'browse';
		}


		$THEME->breadcrumbs[0]->set('icon', $this->imageUrl.'/camera-silver.png');
        $THEME->addBreadcrumb($this->adminUrl, $this->getTitle());

		$tabs = array(
			'browse' => 'Browse',
			'upload' => 'Upload',
			'new-folder' => 'New Folder',
			'import-export' => 'Import / Export'
		);

		$actionUrls = array(
			'browse' => $this->adminUrl.'/browse/',
			'upload' => $this->adminUrl.'/upload/',
			'new-folder' => $this->adminUrl.'/new-folder/',
			'import-export' => $this->adminUrl.'/import-export/'
		);

		$adminTabs = array();
        foreach($tabs as $k=>$title){
            if($k==$req[0]) $class = 'selected';
            else $class = '';
            $adminTabs[] = array(
                'key'=>$k,
                'title' => $title,
                'url' => $actionUrls[$k],
                'class' => $class
            );
        };
        $SMARTY->assign('adminTabs', $adminTabs);

		echo $this->fetchTemplate('/admin/tabs.tpl');

		echo '<div id="admin-content">';

		switch($req[0]){
			case 'upload':
				require($this->dirname.'/actions/upload.php');
			break;
			case 'browse':
			default:
				require($this->dirname.'/actions/browse.php');
			break;
			case 'new-folder':
				require($this->dirname.'/actions/new-folder.php');
			break;
			case 'import-export':
				require($this->dirname.'/actions/import-export.php');
			break;
		}

		echo '</div>';

	}



    function GetConfig($k){
        if(isset($this->imager_config[$k])) return $this->imager_config[$k];
        else if($this->ThrowConfigExceptions) throw new Exception($this->getTitle().'->GetConfig was asked to find a non-existing key: '.$k);
        else return false;
    }

	public function setFile($filepath){

	}


public function getPageActionButtons($blockId, $page){
}

	public function getBlockEditButtons($block){

		$CONFIG = JFX::registry('config');
		$allButtons = array();

		if($block->moduleKey!=$this->keyname){
			return array();
		}

		switch($block->moduleAction){//$block->moduleAction){
            case 'image':
				$button1 = new JFX_Page_Button;
				$button1->pageId = $block->pageid;
				$button1->alternativeText = $this->lang('block_edit_button_alt');
				$button1->moduleName = $this->keyname;
				$button1->moduleMethod = 'updateSettings';
				$button1->imageUrl = $CONFIG->imageUrl.'/admin/icons/camera-silver.png';
				$button1->title = $block->moduleAction.' '.$this->lang('block_edit_button_title');
				$button1->blockId = $block->id;
				$allButtons[] = $button1;
			break;
		}

		return $allButtons;


	}


	public function getBlockActionButtons($blockid, $pageId){
        $CONFIG = JFX::registry('config');

		$block = JFX_Block::getBlockById($blockid, $pageId);

		$allButtons = array();

		switch($block->moduleAction){
            case 'image':
				$button1 = new JFX_Block_Button;
				$button1->pageId = $pageId;
				$button1->alternativeText = $this->lang('block_edit_button_alt');
				$button1->moduleName = $this->keyname;
				$button1->moduleMethod = 'updateSettings';
				$button1->imageUrl = $this->imageUrl.'/camera-silver.png';
				$button1->title = $this->lang('block_edit_button_title');
				$button1->blockId = $blockid;
				$allButtons[] = $button1;
			break;
		}

		return $allButtons;

	}

    public function getBlockActions(){
        return array(
            array(
                'keyname' => 'image',
                'title' => $this->lang('block_action_content_image'),
                'description' => ''
            )
        );
    }

	public function getContentTypeName($action){
		return $this->lang('block_action_content_'.$action);
	}

	public function updateSettings($block){
		
		if(false === ($block instanceof JFX_Block)){
			return;
		}
		$VIEW = JFX::registry('JFX_View');
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
		$CORE = JFX::registry('JFX_Core');
		$SETTINGS = JFX::registry('JFX_Settings');
		$USER = JFX::registry('JFX_User');

		//$file = JFX_Data::newFile($this->keyname, '/home/antz/Pictures/antz.jpg', 'Antz', 'images/def');

//return;

		//var_dump($_GET);
		//return;

		
		require($this->dirname.'/actions/filepicker.php');

	
		
	}


	public function getContent($blockid, $pageid){
		return $this->getContentRaw($blockid, $pageid);
	}

	public function getContentRaw($blockid, $pageid){
		$block = JFX_Block::getBlockById($blockid, $pageid);
		$file = @JFX_Data::getFile($block->getConfig('filepath'), $block->getConfig('filename'), $this->keyname);
		if(!is_object($file) || false==($file instanceof JFX_Data_File)){
			return '';
		}
		return '<img src="'.$this->imageUrl.'/serve.php?filepath='.$file->meta['filepath'].'&amp;filename='.$file->meta['filename'].'" style="width: 100%; height: 100%" />';

	}

	public function createDefaultBlock($action, $blockid, $workspaceid){
	
	}
	public function getDefaultContent($action){
		ob_start();
		require($this->dirname.'/actions/edit.php');
		$res = ob_get_contents();
		ob_end_clean();
		return $res;
	}

    public function install(){
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__)).'/install';
        include('install/install.php');
    }


    public function uninstall(){
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__)).'/install';
        include('install/uninstall.php');
    }





}